package com.wrial.simple;
/*
 * @Author  Wrial
 * @Date Created in 9:54 2020/3/26
 * @Description  最长公共前缀
 */

/**
 * 所有输入只包含小写字母 a-z
 * 输入: ["flower","flow","flight"]
 * 输出: "fl"
 * <p>
 * 输入: ["dog","racecar","car"]
 * 输出: ""
 * 解释: 输入不存在公共前缀。
 */
public class LeetCode_14 {

    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) return "";
        String commonPrefix = strs[0];

        for (int i = 1; i < strs.length; i++) {

            int commonIndex = 0;
            // 一定要注意这个j<strs[i].length()啊啊   此处的commonIndex可以将j外提，省了一个变量空间
            for (int j = 0; j < commonPrefix.length() && j<strs[i].length(); j++) {
                if (commonPrefix.charAt(j) == strs[i].charAt(j)){
                    commonIndex++;
                }else {
                    break;
                }

            }
            // 截取子串
            commonPrefix = commonPrefix.substring(0, commonIndex);
        }

        return commonPrefix;

    }

    public static void main(String[] args) {
        System.out.println(new LeetCode_14().longestCommonPrefix(new String[]{
                "flower","flow","flight"
        }));

    }

}
